<?php
include($_SERVER['DOCUMENT_ROOT'] . '/Biohof/inc/application_settings.php');
include(FILESTORE);
include(IMAGE);


$target = (isset($_REQUEST['T'])) ? $_REQUEST['T'] : null;
switch($target){
	case 'GALLERY_PREVIEW':
		loadGalleryPreview();
		break;
	case 'IMAGE':
		loadImage();
		break;
}


/**
 * loads one image 
 */
function loadImage(){
	$fileId = (isset($_REQUEST['FILE_ID'])) ? $_REQUEST['FILE_ID'] : null;
	$width = (isset($_REQUEST['WIDTH'])) ? $_REQUEST['WIDTH'] : null;
	$height = (isset($_REQUEST['HEIGHT'])) ? $_REQUEST['HEIGHT'] : null;
	
	if (is_numeric($fileId)){
		$sqlObj = Sql_Object::getInstance();
		$sqlObj->connect();
		
		$fs = new Filestore($sqlObj);
		$info = $fs->getFileInfo($fileId);
		
		$image = new Image();
		$image->load($info['path'], $info['physicalname']);
		$image->resize($width, $height);
		$image->display();
		
		$sqlObj->disconnect();
	}
}


/**
 * loads one image from the gallery
 */
function loadGalleryPreview(){
	$galleryId = (isset($_REQUEST['GALLERY_ID'])) ? $_REQUEST['GALLERY_ID'] : null;
	if (is_numeric($galleryId)){
		$sqlObj = Sql_Object::getInstance();
		$sqlObj->connect();
		
		$fileId = getRandomFileId($galleryId, $sqlObj);
		
		$fs = new Filestore($sqlObj);
		$info = $fs->getFileInfo($fileId);
		
		$image = new Image();
		$image->load($info['path'], $info['physicalname']);
		$image->resize(190, 170);
		$image->display();
		
		$sqlObj->disconnect();
	}
}


/**
 * returns a random fileId from given gallery
 * @param 		int		 $galleryId
 * @param 		mixed	 $sqlObj
 * @return		int		 $fileId
 */
function getRandomFileId($galleryId, $sqlObj){
	$sql = 'select file_id from ' . DB_BIO . '.gallery_image_view where gallery_id = ? and active = ?';
	$params = array($galleryId, ACTIVE);
	$fileIds = array();
	$index = 0;
	
	$sqlObj->execute($sql, $params);
	while (($row = $sqlObj->fetch()) != null){
		$fileIds[$index] = $row['file_id'];
		$index++;
	}
	
	$index = rand(0, ($index-1));
	$fileId = $fileIds[$index];
	return $fileId;
}